package com.snapan.controller;

import com.snapan.common.PageResult;
import com.snapan.entity.ShareFile;
import com.snapan.service.ShareService;
import com.snapan.service.UserFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 分享文件控制器
 */
@RestController
@RequestMapping("/api/share")
public class ShareController {

    @Autowired
    private ShareService shareService;
    
    @Autowired
    private UserFileService userFileService;

    /**
     * 获取我的分享列表
     */
    @GetMapping("/list")
    public Map<String, Object> getShareList(@RequestParam int pageSize,
                                           @RequestParam int pageNo,
                                           @RequestParam int userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            PageResult<ShareFile> page = shareService.getShareList(pageSize, pageNo, userId);
            result.put("success", true);
            result.put("data", page);
            result.put("message", "获取分享列表成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取分享列表失败：" + e.getMessage());
            
        }
        return result;
    }

    /**
     * 根据分享码获取分享信息
     */
    @GetMapping("/access/{shareCode}")
    public Map<String, Object> getShareByToken(@PathVariable String shareCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            System.out.println("获取分享信息，分享码: " + shareCode);
            ShareFile shareFile = shareService.getShareByToken(shareCode);
            
            if (shareFile != null) {
                // 检查分享状态
                if (shareFile.getStatus() != 1) {
                    result.put("success", false);
                    result.put("message", "分享已被禁用");
                    return result;
                }
                
                // 检查是否过期
                if (shareFile.getExpireTime() != null && 
                    shareFile.getExpireTime().before(new Date())) {
                    result.put("success", false);
                    result.put("message", "分享已过期");
                    return result;
                }
                
                // 构造返回数据
                Map<String, Object> data = new HashMap<>();
                
                // 分享基本信息（隐藏密码）
                Map<String, Object> shareInfo = new HashMap<>();
                shareInfo.put("id", shareFile.getId());
                shareInfo.put("shareCode", shareFile.getShareCode());
                shareInfo.put("shareTitle", shareFile.getShareTitle());
                shareInfo.put("password", shareFile.getPassword() != null ? "***" : null); // 隐藏密码
                shareInfo.put("expireTime", shareFile.getExpireTime());
                shareInfo.put("fileId", shareFile.getFileId());
                data.put("shareInfo", shareInfo);
                
                // 如果设置了密码，返回提示信息（不包含文件列表）
                if (shareFile.getPassword() != null && !shareFile.getPassword().isEmpty()) {
                    data.put("requiresPassword", true);
                    data.put("files", new java.util.ArrayList<>());
                } else {
                    // 没有密码，直接返回文件列表
                    data.put("requiresPassword", false);
                    java.util.List<Map<String, Object>> files = new java.util.ArrayList<>();
                    Map<String, Object> fileInfo = new HashMap<>();
                    fileInfo.put("id", shareFile.getId());
                    fileInfo.put("fileName", shareFile.getFileName());
                    fileInfo.put("fileSize", shareFile.getFileSize());
                    fileInfo.put("fileType", shareFile.getFileType());
                    fileInfo.put("filePath", shareFile.getFilePath());
                    fileInfo.put("isDirectory", shareFile.getIsDirectory());
                    files.add(fileInfo);
                    data.put("files", files);
                }
                
                result.put("success", true);
                result.put("data", data);
                result.put("message", "获取分享信息成功");
            } else {
                result.put("success", false);
                result.put("message", "分享不存在");
            }
        } catch (Exception e) {
            System.err.println("获取分享信息失败: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取分享信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 创建分享
     */
    @PostMapping("/create")
    public Map<String, Object> createShare(@RequestBody Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            System.out.println("收到创建分享请求: " + requestData.toString());
            
            // 从请求中提取数据
            Long fileId = Long.valueOf(requestData.get("fileId").toString());
            String shareTitle = requestData.get("shareTitle").toString();
            Long userId = Long.valueOf(requestData.get("userId").toString());
            
            // 日期处理
            Date expireTime = null;
            if (requestData.get("expireTime") != null && !requestData.get("expireTime").toString().equals("null")) {
                String expireTimeStr = requestData.get("expireTime").toString();
                try {
                    expireTime = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(expireTimeStr);
                } catch (Exception e) {
                    System.err.println("日期解析失败: " + expireTimeStr);
                }
            }
            
            // 是否需要密码
            boolean enablePassword = requestData.get("enablePassword") != null 
                && Boolean.parseBoolean(requestData.get("enablePassword").toString());
            
            System.out.println("用户ID: " + userId);
            System.out.println("文件ID: " + fileId);
            System.out.println("是否启用密码: " + enablePassword);
            
            // 创建 ShareFile 对象
            ShareFile shareFile = new ShareFile();
            shareFile.setFileId(fileId);
            shareFile.setShareTitle(shareTitle);
            shareFile.setUserId(userId);
            shareFile.setExpireTime(expireTime);
            
            // 调用服务层创建分享（这里会自动生成密码）
            ShareFile createdShare = shareService.createShare(shareFile, enablePassword);
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("shareCode", createdShare.getShareCode());
            data.put("password", createdShare.getPassword());
            
            result.put("success", true);
            result.put("data", data);
            result.put("message", "创建分享成功");
            shareService.syncShareFileToEs(createdShare.getId());
        } catch (Exception e) {
            System.err.println("创建分享失败: " + e.getMessage());
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "创建分享失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 验证分享密码
     */
    @PostMapping("/verify/{shareCode}")
    public Map<String, Object> verifySharePassword(@PathVariable String shareCode, 
                                                   @RequestBody Map<String, Object> requestData) {
        Map<String, Object> result = new HashMap<>();
        try {
            String password = requestData.get("password").toString();
            
            // 验证密码
            ShareFile shareFile = shareService.verifyPassword(shareCode, password);
            
            if (shareFile != null) {
                // 密码正确，返回文件信息
                Map<String, Object> data = new HashMap<>();
                
                // 分享基本信息
                Map<String, Object> shareInfo = new HashMap<>();
                shareInfo.put("id", shareFile.getId());
                shareInfo.put("shareCode", shareFile.getShareCode());
                shareInfo.put("shareTitle", shareFile.getShareTitle());
                shareInfo.put("fileId", shareFile.getFileId());
                shareInfo.put("expireTime", shareFile.getExpireTime());
                data.put("shareInfo", shareInfo);
                data.put("expireTime", shareFile.getExpireTime());
                
                // 构造文件数组
                java.util.List<Map<String, Object>> files = new java.util.ArrayList<>();
                Map<String, Object> fileInfo = new HashMap<>();
                fileInfo.put("id", shareFile.getId());
                fileInfo.put("fileName", shareFile.getFileName());
                fileInfo.put("fileSize", shareFile.getFileSize());
                fileInfo.put("fileType", shareFile.getFileType());
                fileInfo.put("filePath", shareFile.getFilePath());
                fileInfo.put("isDirectory", shareFile.getIsDirectory());
                files.add(fileInfo);
                
                data.put("files", files);
                
                result.put("success", true);
                result.put("data", data);
                result.put("message", "密码验证成功");
            } else {
                result.put("success", false);
                result.put("message", "密码错误，请重试");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "密码验证失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 更新分享
     */
    @PutMapping("/{id}")
    public Map<String, Object> updateShare(@PathVariable Long id, @RequestBody ShareFile shareFile) {
        Map<String, Object> result = new HashMap<>();
        try {
            shareFile.setId(id);
            boolean success = shareService.updateShare(shareFile);
            if (success) {
                result.put("success", true);
                result.put("message", "更新分享成功");
            } else {
                result.put("success", false);
                result.put("message", "分享不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新分享失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除分享
     */
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteShare(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = shareService.deleteShare(id);
            if (success) {
                result.put("success", true);
                result.put("message", "删除分享成功");
            } else {
                result.put("success", false);
                result.put("message", "分享不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除分享失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 记录分享访问
     */
    @PostMapping("/access/{shareCode}/visit")
    public Map<String, Object> recordAccess(@PathVariable String shareCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = shareService.recordAccess(shareCode);
            result.put("success", success);
            result.put("message", success ? "记录访问成功" : "分享不存在或已过期");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "记录访问失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 下载分享文件
     */
    @GetMapping("/download/{shareCode}/{fileId}")
    public void downloadShareFile(@PathVariable String shareCode, 
                                @PathVariable Long fileId,
                                HttpServletResponse response) {
        try {
            // 验证分享码
            ShareFile shareFile = shareService.getShareByToken(shareCode);
            if (shareFile == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("分享不存在或已过期");
                return;
            }
            
            // 检查分享是否过期
            if (shareFile.getExpireTime() != null && 
                shareFile.getExpireTime().before(new java.util.Date())) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.getWriter().write("分享已过期");
                return;
            }
            
            // 检查分享状态
            if (shareFile.getStatus() != 1) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.getWriter().write("分享已被禁用");
                return;
            }
            
            // 验证fileId是否匹配（fileId应该是user_file.id，需要转换为file_base.id）
            // fileId应该等于shareFile.getFileId()
            if (!shareFile.getFileId().equals(fileId)) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().write("文件ID不匹配");
                return;
            }
            
            // 获取UserFile获取fileBaseId
            com.snapan.entity.UserFile userFile = userFileService.getById(fileId);
            if (userFile == null || userFile.getFileBaseId() == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("文件不存在");
                return;
            }
            
            // 更新下载次数
            shareService.recordAccess(shareCode);
            
            // 重定向到FileBaseController的下载接口（使用fileBaseId）
            response.sendRedirect("/api/filebase/download/" + userFile.getFileBaseId());
            
        } catch (Exception e) {
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.getWriter().write("下载失败：" + e.getMessage());
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }


    /**
     * 测试分享功能是否正常
     */
    @GetMapping("/test")
    public Map<String, Object> testShare() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 测试数据库连接
            result.put("success", true);
            result.put("message", "分享功能测试成功");
            result.put("timestamp", new java.util.Date());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "分享功能测试失败：" + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
